
/***********************************************************************
 * Load class
 * 
 * Implements the 'save' command
 *
 * Signature:
 *  public static Orbit create ();
 *  public String name ();
 *  public boolean execute (String[] arguments);
 ***********************************************************************/
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Load:
 * @author Dan & Adam
 */
public class Load extends Command {

  /**
   * Constructor:
   */
  protected Load () {
    super("load");
  }

  /**
   * Creator:
   * @return
   */
  public static Load create () {
    return new Load();
  }

  /**
   * LoadGameState:
   * @param filename
   */
  @SuppressWarnings("deprecation") 
  public void loadGameState(String filename) {
    try {
      // DataInputStream
      DataInputStream in = new DataInputStream(new FileInputStream(filename));
      // Load from File
      SpaceGame.loadGameStateFromJSON(new JSONObject(in.readLine()));
      in.close();
      System.out.println("Game Loaded: " + filename);
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException("Load Error");
    }
  }

  /**
   * FileExists checks if a file exists.
   * @param filename
   * @return
   */
  private boolean fileExists(String filename) {
    boolean exists = new File(filename).exists();
    return exists;
  }

  /* (non-Javadoc)
   * @see Command#execute(java.lang.String[])
   */
  public boolean execute (String[] args) {
    if (args.length != 2) {
      System.out.println("Incorrect Usage, Try 'load <savefilename>'");
    } else if(fileExists(args[1])) {
      loadGameState(args[1]);
    } else {
      System.out.println("Invalid Filename, No Game " + args[1] + " Exists.");
    }
    return false;
  }
}